package com.afinal.intelligencetrash.ui.MapUtils;

import com.afinal.intelligencetrash.R;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 厂里帅小伙 on 2/23 0023.
 * 该类用来管理地图中的标记，添加，删除，更新
 */

public class MarkerManager {
    private Map<Long, Marker> markers = new HashMap<>();
    private AMap mMap = null;
    public MarkerManager(AMap mMap) {
        this.mMap = mMap;
    }


    private MarkerOptions getOptions(MarkerDo markerDo){
        MarkerOptions options = new MarkerOptions();
        return markerDo.initMarkerOptions(options);
    }


    public void setMarker(MarkerDo markerDo){
        Marker marker = markers.get(markerDo.getTrashId());
        if(marker == null){
            addMarker(markerDo);
            return;
        }
        if(!marker.isInfoWindowShown()){
            modifyMarker(markerDo);
        }
    }

    public void setMarkersFormList(List<MarkerDo> markerInfos){
        for (MarkerDo temp : markerInfos){
            setMarker(temp);
        }

    }

    private void addMarker(MarkerDo markerDo){
        if(markerDo != null){
            MarkerOptions options = getOptions(markerDo);
            Marker marker = mMap.addMarker(options);
            marker.setObject(markerDo);
            markers.put(markerDo.getTrashId(), marker);
        }
    }


    public void removeMarker(long trashId){
        Marker temp = markers.get(trashId);
        if (temp != null) {
            temp.remove();
            markers.remove(trashId);
        }
    }

    public void removeAllMarkers(){
        for (Map.Entry<Long, Marker> temp : markers.entrySet()) {
            temp.getValue().remove();
        }
        markers.clear();
    }

    private void modifyMarker(MarkerDo markerDo){
        if(markerDo != null){
            removeMarker(markerDo.getTrashId());
            addMarker(markerDo);
        }
    }

    public void moveToMarkerByTrashId(long trashId){
        if(markers != null){
            Marker temp = markers.get(trashId);
            if (temp != null){
                mMap.moveCamera(CameraUpdateFactory.changeLatLng(temp.getPosition()));
            }
        }
    }

    public void moveToMarker(Marker marker){
        if(marker != null){
            mMap.moveCamera(CameraUpdateFactory.changeLatLng(marker.getPosition()));
        }
    }
    public void setMarkerClickListener(AMap.OnMarkerClickListener listener) {
        mMap.setOnMarkerClickListener(listener);
    }

    public void setMarkerDragListener(AMap.OnMarkerDragListener listener){
        mMap.setOnMarkerDragListener(listener);
    }
}
